<template>
  <div ref="myEditor" class="myEditor"></div>
</template>

<script lang="ts">
import Vue from 'vue'
import E from 'wangeditor'
import { uploadFile } from './api/index'
export default Vue.extend({
  name: 'myEditor',
  data () {
    return {
      editor: null
    }
  },
  mounted () {
    console.log('mounted')
    this.editorInit()
  },

  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    editorInit () {
      this.editor = new E(this.$refs.myEditor)
      // 配置触发 onchange 的时间频率，默认为 200ms
      this.editor.config.onchangeTimeout = 500 // 修改为 500ms
      this.editor.config.onchange = (newHtml: string) => {
        console.log('change 之后最新的 html', newHtml)
        this.$emit('input', newHtml)
        // if(newHtml!==this.value){

        // }
      }
      this.editor.config.customUploadImg = async (resultFiles: any, insertImgFn: any) => {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法

        // 上传图片，返回结果，将图片插入到编辑器中
        // insertImgFn(imgUrl)
        console.log(resultFiles)
        console.log(insertImgFn)
        const fd = new FormData()
        fd.append('file', resultFiles[0])
        const res = await uploadFile(fd)
        console.log(res)
        insertImgFn(res.data.data.name)
      }
      this.editor.create()
      console.log(this.value)
      this.editor.txt.html(this.value)
    }
  },
  watch: {
    value: {
      handler (n) {
        this.editor.txt.html(n)
      }
    }
  }
})
</script>

<style lang="scss" scoped></style>
